# -*- encoding:utf-8 -*-
"""
@作者：张福隆
@时间：2020/04/03
"""
import os
import time
import json
import base64
import requests


def Send(template,merge):
    postData = {
        'api_key':'XLWiZ4FyzIrfr79HZkx4kgNN_hw2EIPZ',
        'api_secret':'2bq_E73aeK9_eCViS-468w_pRgyDP9sM',
        'template_base64':Code(template), #模板人像
        'merge_base64':Code(merge)      #转化人像
    }
    res = requests.post("https://api-cn.faceplusplus.com/imagepp/v1/mergeface",data=postData)
    return res.text
def Code(name):
    with open(name, 'rb') as f:
        base64_data = base64.b64encode(f.read())
        base64_code = base64_data.decode()
        return base64_code
def Save(template,merge,name):
    jsonData = json.loads(Send(template,merge))
    imgData = base64.b64decode(jsonData["result"])
    file = open("C:\\Users\\linux\\Desktop\\转换\\"+name, 'wb')
    file.write(imgData)
    file.close()
def all_path(dirname):
    result = []#所有的文件
    for maindir, subdir, file_name_list in os.walk(dirname):
        for filename in file_name_list:
            apath = os.path.join(maindir, filename)#合并成一个完整路径
            result.append(apath)
    return result,file_name_list
def main():
    merge = "C:\\Users\\linux\\Desktop\\张学友.jpg"
    result,file_name_list = all_path("C:\\Users\\linux\\Desktop\\精华")
    for i in range(len(result)):
        Save(result[i],merge,file_name_list[i])
        time.sleep(1)  # 休眠1秒
    #Save("C:\\Users\\linux\\Desktop\\447.jpg", merge, "精彩.jpg")
if __name__ == "__main__":
    main()